package com.lmc.form.script;

import com.free.bsf.core.base.BsfException;
import com.free.bsf.core.db.DbHelper;
import com.free.bsf.core.http.HttpClient;
import com.free.bsf.core.util.*;
import com.lmc.form.dao.dal.paas_form_model_dal;
import io.swagger.annotations.Api;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import lombok.val;
import org.apache.http.entity.ContentType;

import javax.sql.DataSource;
import java.util.*;

public class ApiScript {
    protected String scriptInfo;
    //表单
    public LinkedHashMap form = new LinkedHashMap();

    public ApiScript(String scriptInfo, LinkedHashMap form){
        this.scriptInfo=scriptInfo;
        this.form = form;
    }
    //获取表
    public ApiTable getTable(String title){
        val value = getDesign(title);
        if(value == null){
            throw new BsfException("表格:"+StringUtils.nullToEmpty(title)+"不存在");
        }
        ApiTable.PagerInput pagerInput = JsonUtils.deserialize(JsonUtils.serialize(value),ApiTable.PagerInput.class);
        return new ApiTable(this,pagerInput);
    }
    //自定义表单数据通过title获取
    public Object getDesign(String title){
        if(title==null)
            return null;
        val jsonFiled=getJsonField(form);
        if(jsonFiled!=null) {
            val formValue = form.get(jsonFiled);
            if(formValue!=null&&formValue instanceof List){
                val formList = (List<LinkedHashMap>) formValue;
                for(val formObj:formList){
                    if(title.equals(formObj.get("title"))){
                        return formObj.get("value");
                    }
                }
            }
        }
        return null;
    }
    //自定义表单数据通过title更新
    public void setDesign(String title,Object value){
        if(title==null)
            return;
        val jsonFiled=getJsonField(form);
        if(jsonFiled!=null) {
            val formValue = form.get(jsonFiled);
            if(formValue!=null&&formValue instanceof List){
                val formList = (List<LinkedHashMap>) formValue;
                for(val formObj:formList){
                    if(title.equals(formObj.get("title"))){
                         formObj.put("value",value);
                         return;
                    }
                }
            }
        }
    }
    //普通日志
    public void log(Object info){
        LogUtils.info(ApiScript.class,"bsf","动态脚本普通日志:"+scriptInfo+"=>"+JsonUtils.serialize(info));
        DebugUtil.webDebug(info);
    }
    //调试日志
    public void debug(Object info){
        LogUtils.debug(ApiScript.class,"bsf","动态脚本调试日志:"+scriptInfo+"=>"+JsonUtils.serialize(info));
        DebugUtil.webDebug(info);
    }
    //转json
    public String toJson(Object json){
        return  JsonUtils.serialize(toJavaObject(json));
    }
    //来自json
    public Object fromJson(String json){
        return  JsonUtils.deserialize(json,Object.class);
    }

    //转java类型
    public Object toJavaObject(Object obj) {
        if(obj == null ||!(obj instanceof ScriptObjectMirror)){
            return obj;
        }
        ScriptObjectMirror mirror = (ScriptObjectMirror) obj;
        if (mirror.isEmpty()) {
            return null;
        }
        if (mirror.isArray()) {
            List<Object> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : mirror.entrySet()) {
                Object result = entry.getValue();
                if (result instanceof ScriptObjectMirror) {
                    list.add(toJavaObject((ScriptObjectMirror) result));
                } else {
                    list.add(result);
                }
            }
            return list;
        }

        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String, Object> entry : mirror.entrySet()) {
            Object result = entry.getValue();
            if (result instanceof ScriptObjectMirror) {
                map.put(entry.getKey(), toJavaObject((ScriptObjectMirror) result));
            } else {
                map.put(entry.getKey(), result);
            }
        }
        return map;
    }
    //开启缓存
    public ApiScriptCache cache(int cacheTime){
        return new ApiScriptCache(this,cacheTime);
    }
    //执行sql
    public Object querySql(String sql,Object...ps){
        try{
        val r = DbHelper.get(ContextUtils.getBean(DataSource.class,false),(c)->{
            return c.executeList(sql,ps);
        });
        return  r;
        }catch (Exception e){
            val msg = "动态sql出错:"+sql+",参数:"+JsonUtils.serialize(ps);
            LogUtils.error(ApiScript.class,"bsf",msg,e);
            throw new BsfException(msg);
        }
    }
    //http请求
    public Object httpPost(String url,Object json){
        HttpClient.Params params = HttpClient.Params
                .custom()
                .setContentType(ContentType.APPLICATION_JSON)
                .add(json).build();
        return HttpClientUtils.system().post(url, params);
    }

    //http请求 form请求支持
    public Object httpPostForm(String url,Object json){
        HttpClient.Params params = HttpClient.Params
                .custom()
                .setContentType(ContentType.APPLICATION_FORM_URLENCODED)
                .add(json).build();
        return HttpClientUtils.system().post(url, params);
    }
    //http请求 get
    //http请求 form请求支持
    public Object httpGet(String url){
        return HttpClientUtils.system().get(url);
    }
    //识别Design form json字段
    private String getJsonField(LinkedHashMap request){
        List<String> fields = new ArrayList<>();
        for(val f:request.keySet()){
            if(f.toString().toLowerCase().contains("json")){
                fields.add(f.toString());
            }
        }
        if(fields.size()==0)
            return null;
        for(val field:fields){
            if(field.equalsIgnoreCase("json_data")||field.equalsIgnoreCase("custom_json")){
                return field;
            }
        }
        return fields.get(0);
    }
}


http://lmc-eureka-server2.basic-platform:8080


#!/bin/bash

for i in {1..2000000}; do 

        code=`curl -I -m 10 -o /dev/null -s -w %{http_code} http://lmc-eureka-server2.basic-platform:8080`
        echo $code >> url_test.log
        #sleep 1

done

#!/bin/bash

for i in {1..2000000}; do 

        code=`curl -I -m 10 -o /dev/null -s -w %{http_code} http://172.16.1.108:30005`
        echo $code >> url_test.log
        #sleep 1

done


#!/bin/bash

for i in {1..2000000}; do 

        code=`curl -I -m 10 -o /dev/null -s -w %{http_code} http://pro-eureka-server1.linkmore.com/`
        echo $code >> url_test.log
        #sleep 1

done